#encoding=utf-8
from rest_framework import permissions
from django.utils import timezone
from django.conf import settings
from rest_framework import authentication, exceptions


class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to edit it.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True

        # Write permissions are only allowed to the owner of the snippet.
        return obj.owner == request.user


class IsUserAuthenticated(permissions.BasePermission):
    """
    客户登陆校验
    """
    def has_permission(self, request, view):
        user = request.user
        if user.id:
            if user.last_login == None:
                return False
            if (timezone.now() - user.last_login).total_seconds() > settings.LOGIN_TIMEOUT:
                #超时了
                raise exceptions.AuthenticationFailed('令牌失效，请重新登录！')
            else:
                user.last_login = timezone.now()
                user.save()
                return True
        else:
            return False


# class IsCustomerAuthenticatedAndRead(permissions.BasePermission):
#     """
#     客户登陆后只有读权限
#     """
#     def has_permission(self, request, view):
#         user = request.user
#         if user.id and hasattr(user, 'customer'):
#             return request.method in permissions.SAFE_METHODS
#         else:
#             return False

